import React from 'react';
import PageTitle from 'component/page-title/PageTitle.jsx';
import MUtil from 'util/MUtil.jsx';
const mUtil = new MUtil();
import ProductService from 'service/ProductService.jsx';
const productService = new ProductService();
import Pagination from 'util/Pagination.jsx';
import TableList from 'util/TableList.jsx';
import { Link } from 'react-router-dom';
import ProductSearch from 'page/product/index/ProductSearch.jsx';

import './product-list.styl';

export default
  class ProductList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      pageNum: 1,
      firstLoading: true,
      listType: 'list'
    };
  }

  /**
   * 加载商品列表
   */
  loadProductList() {
    let listParam = {};
    listParam.listType = this.state.listType;
    listParam.pageNum = this.state.pageNum;

    // 如果是搜索的话，需要传入搜索类型和搜索关键字
    if (this.state.listType === 'search') {
      listParam.searchType = this.state.searchType;
      listParam.keyword = this.state.searchKeyword;
    }
    // 请求接口
    productService
      .getProductList(listParam)
      .then(res => {
        this.setState(res.data, () => {
          this.setState({
            firstLoad: false
          })
        });
      }, errMsg => {
        this.setState({
          list: []
        });
        mUtil.errorTips(errMsg);
      });
  }

  /**
   * 搜索
   */
  onSearch(searchType, searchKeyword) {
    let listType = searchKeyword === '' ? 'list' : 'search';
    this.setState({
      listType,
      pageNum: 1,
      searchType,
      searchKeyword,
    }, () => this.loadProductList());
  }

  componentDidMount() {
    this.loadProductList();
  }

  onSetProductStatus(e, productId, currentStatus) {
    let newStatus = currentStatus == 1 ? 2 : 1,
      comfirmTips = currentStatus == 1 ? '确定要下架该商品吗？' : '确定要商家该商品吗？'
    if (confirm(comfirmTips)) {
      productService.setProductStatus({
        productId,
        status: newStatus
      }).then(res => {
        mUtil.successTips(res.data);
        this.loadProductList();
      }, errMsg => {
        mUtil.errorTips(errMsg);
      });
    }
  }
  onPageNumChange(pageNum) {
    this.setState({ pageNum }, () => this.loadProductList());
  }

  render() {
    let listBody = this.state.list
      .map((user, index) => {
        return (
          <tr key={index}>
            <td>{user.id}</td>
            <td>{user.username}</td>
            <td>{user.email}</td>
            <td>{user.phone}</td>
            <td>{new Date(user.createTime).toLocaleString()}</td>
          </tr>);
      });

    let listError = (
      <tr>
        <td colSpan="5" className="text-center">{this.state.firstLoad ? '正在加载...' : '没有找到相应的结果'}</td>
      </tr>
    );

    let tableBody = this.state.list.length > 0 ? listBody : listError;

    let tableHeads = [
      { name: '商品ID', width: '10%' },
      { name: '商品信息', width: '50%' },
      { name: '价格', width: '10%' },
      { name: '状态', width: '15%' },
      { name: '操作', width: '15%' },
    ];
    return (
      <div id="page-wrapper">
        <PageTitle title="商品列表" >
          <div className="page-header-right">
            <Link className="btn btn-primary" to='/product/save'>
              <i className="fa fa-plus"></i>
              <span>添加商品</span>
            </Link>
          </div>
        </PageTitle>
        <ProductSearch onSearch={(searchType, searchKeyword) => this.onSearch(searchType, searchKeyword)} />
        <TableList tableHeads={tableHeads}>
          {
            this.state.list.map((product, index) => {
              return (
                <tr key={index}>
                  <td>{product.id}</td>
                  <td>
                    <p>{product.name}</p>
                    <p>{product.subtitle}</p>
                  </td>
                  <td>￥{product.price}</td>
                  <td>
                    <p>{product.status == 1 ? '在售' : '已下架'}</p>
                    <button className="btn btn-warning btn-xs"
                      onClick={e => this.onSetProductStatus(e, product.id, product.status)}>{product.status == 1 ? '下架' : '上架'}</button>
                  </td>
                  <td>
                    <Link className="operate" to={`/product/detail/${product.id}`}>详情</Link>
                    <Link className="operate" to={`/product/save/${product.id}`}>编辑</Link>
                  </td>
                </tr>
              );
            })
          }
        </TableList>
        <Pagination current={this.state.pageNum}
          total={this.state.total}
          onChange={pageNum => this.onPageNumChange(pageNum)} />
      </div>
    );
  }
}